package com.qlylkj.lbk.ui.news

import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.forest.core.etx.startKtxActivity
import com.forest.core.etx.toast
import com.qlylkj.lbk.R
import com.qlylkj.lbk.app.addHost
import com.qlylkj.lbk.base.BaseVMActivity
import com.qlylkj.lbk.base.WebViewActivity
import com.qlylkj.lbk.model.bean.News
import kotlinx.android.synthetic.main.activity_news.*
import kotlinx.android.synthetic.main.layout_toolbar.*

class NewsActivity: BaseVMActivity<NewsViewModel>() {


    private val newsAdapter by lazy { NewsAdapter() }

    override fun providerVMClass() = NewsViewModel::class.java

    override fun setLayoutId() = R.layout.activity_news

    override fun initView() {
        toolbar.setNavigationOnClickListener {finish()}
        toolbarTitle.text = "链改新闻"
        newsRefreshLayout.apply {
            setOnRefreshListener {
                getNewsList(true)
            }
            setOnLoadMoreListener {
                getNewsList(false)
            }
        }
        newsRecyclerView.apply {
            layoutManager = LinearLayoutManager(this@NewsActivity)
            adapter = newsAdapter.apply {
                setOnItemClickListener { adapter, _, position ->
                    val news = adapter.getItem(position) as? News
                    news?.apply {
                        startKtxActivity<WebViewActivity>( values = mutableListOf(WebViewActivity.TITLE to title,WebViewActivity.URL to jumpUrl.addHost()))
                    }
                }
            }
        }
    }

    override fun initData() {
        getNewsList(true)
    }

    override fun startObserve() {
        super.startObserve()
        mViewModel.apply {
            uiState.observe(this@NewsActivity, Observer { uiModel ->
                uiModel?.run {
                    newsRefreshLayout.finishRefresh()
                    newsRefreshLayout.finishLoadMore()
                    if(newsList.isNotEmpty()){
                        if(isRefresh){
                            newsRefreshLayout.resetNoMoreData()
                            newsAdapter.replaceData(newsList)
                        }else{
                            newsAdapter.addData(newsList)
                        }
                    }else{
                        newsRefreshLayout.finishLoadMoreWithNoMoreData()
                        newsRefreshLayout.setEnableFooterFollowWhenNoMoreData(true)
                    }
                    showError?.let {
                        toast(it)
                    }
                }
            })
        }
    }

    private fun getNewsList(isRefresh: Boolean){
        mViewModel.getNewsList(isRefresh)
    }
}